package com.ruoyi.product.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.manufacturer.domain.DjManufacturer;
import com.ruoyi.material.mapper.MateProductMapper;
import com.ruoyi.procurement.mapper.ProcurementOrderMapper;
import com.ruoyi.product.domain.*;
import com.ruoyi.product.mapper.AICodeMapper;
import com.ruoyi.product.mapper.ProductMapper;
import com.ruoyi.product.service.ProductServer;
import com.ruoyi.productProof.mapper.ProductProofMapper;
import com.ruoyi.purchase.mapper.PurchaseOrderMapper;
import com.ruoyi.sale.mapper.SaleorderMapper;
import com.ruoyi.scope.domain.Scope;
import com.ruoyi.warehousing.domain.WarehouseStatisticsVo;
import com.ruoyi.warehousing.service.WarehousingService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.lang.Integer.parseInt;

@Service
public class ProductServiceImpl implements ProductServer {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductProofMapper productProofMapper;

    @Autowired
    private AICodeMapper aiCodeMapper;

    @Autowired
    private ProcurementOrderMapper procurementOrderMapper;

    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;

    @Autowired
    private SaleorderMapper saleorderMapper;
    @Autowired
    private WarehousingService warehousingService;


    /**
     * 查询产品信息
     *
     * @return 结果
     */

    @Override
    public List<Product> selectProductList(Product product) {
        //product.setDeptId(ShiroUtils.getSysUser().getCompanyId());
        return productMapper.selectProductList(product);
    }

    @Override
    public List<Product> selectProductProofListes(List<Map> saleGoodsModelMaps) {
        return productMapper.selectProductProofListes(saleGoodsModelMaps);
    }

    /**
     * 插入产品信息
     *
     * @param product 产品信息
     * @return 结果
     */
    @Override
    @Transactional
    public String insertProduct(Product product, List<ProductModel> productModels, List<ProductRelation> productRelations) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        product.setCreateBy(sysUser.getUserName());
        product.setDeptId(sysUser.getCompanyId());

        Long productId = 0L;
        if (product.getProductProofAddress() != null && !product.getProductProofAddress().isEmpty()) {
            product.setProductProofAddress(product.getProductProofAddress().replaceAll("/profile/upload", ""));
        }

        int i = productMapper.insertProductId(product);
        productMapper.updateProductId(product);
        productId = product.getSelectId();

        if (productModels != null || productModels.size() != 0) {
            //获取产品信息列表,创建新的图片集合
            //    List<PictureMemory> pictureMemoryList = new ArrayList<PictureMemory>();
            //创建新的数组存储插入成功的id 验证失败后 删除插入成功的数据
            int a = 0;
            ArrayList<Long> longs = new ArrayList<>();
            for (ProductModel productModel : productModels) {
                a++;
                productModel.setProductId(productId);
                productModel.setDeptId(sysUser.getCompanyId());
                productModel.setCreateBy(sysUser.getUserName());
                if (productMapper.selectProductProductType(productModel) != null) {
                    String s = "第" + a + "行产品的型号规格不唯一，请重新输入，请在型号规格前或后添加@#！~！";
                    productMapper.removeProduct(product.getProductId());
                    if (longs.size() != 0) {
                        for (Long aLong : longs) {
                            productMapper.deleteProductModel(aLong);
                        }
                    }
                    return s;
                }
                if (productMapper.selectProductModelCode(productModel) != null) {
                    String s = "第" + a + "行产品的型号为一码不唯一，请重新输入！";
                    productMapper.removeProduct(product.getProductId());
                    if (longs.size() != 0) {
                        for (Long aLong : longs) {
                            productMapper.deleteProductModel(aLong);
                        }
                    }
                    return s;
                }
                productMapper.insertProductModel(productModel);
                longs.add(productModel.getModelNo());
              /*  if (productModel.getPictureMemory() != null) {
                    //循环产品信息集合,获取图片信息列表
                    for (PictureMemory model : productModel.getPictureMemory()) {
                        //遍历图片列表
                        model.setModelNo(productModel.getModelNo());
                        pictureMemoryList.add(model);
                    }
                }*/
            }
            /*if (pictureMemoryList.size() != 0) {
                productMapper.insertPictureMemory(pictureMemoryList);
            }*/

        }
        if (productRelations != null) {
            for (ProductRelation productRelation : productRelations) {
                productRelation.setDeptId(SecurityUtils.getDeptId());
                productRelation.setProductId(productId);
                productMapper.addMateProductRelation(productRelation);

            }
        }
        if (productModels != null || productModels.size() != 0) {
            return i + "";
        } else {
            throw new RuntimeException("请选择产品规格/型号");
        }

    }

    /**
     * 删除产品信息
     *
     * @param productId 需要删除的产品ID
     * @return 结果
     */
    @Override
    @Transactional
    public int removeProduct(Long productId) {
        Map<String, Object> map1 = new HashMap<>();
        Long companyId = ShiroUtils.getSysUser().getCompanyId();
        map1.put("companyId", companyId);
        map1.put("productId", productId);
        //查询入库订单
        List<Long> longs1 = procurementOrderMapper.selectDeleteProduct(map1);
        //查询采购订单
        List<Long> longs2 = purchaseOrderMapper.selectDeleteProduct(map1);
        //查询销售订单
        List<Long> longs3 = saleorderMapper.selectDeleteProduct(map1);
        if (longs1.size() != 0 || longs2.size() != 0 || longs3.size() != 0) {
            return -1;
        }
        Map<Object, Object> map = new HashMap<>();
        if (productMapper.selectProductModelByIds(productId) != null) {
            //存储需要删除的产品
            List<Long> list1 = new ArrayList<>();
            //需要删除的产品图片
            List<Long> list = new ArrayList<>();
            for (Long modelNo : productMapper.selectProductModelByIds(productId)) {
                if (productMapper.selectPictureMemoryByIds(modelNo) != null) {
                    for (Long pictureNo : productMapper.selectPictureMemoryByIds(modelNo)) {
                        list.add(pictureNo);
                    }
                }
                list1.add(modelNo);
            }
            if (list.size() != 0) {
                productMapper.deletePictureMemoryList(list);
            }

            if (list1.size() != 0) {
                productMapper.deleteProductModelList(list1);
            }
        }
        //查询产品的注册证信息
        List<Long> longs = productProofMapper.selectProductProofByProductId(productId);
        if (longs.size() != 0) {
            productProofMapper.deleteProductProof(longs);
        }
        AICode aiCode = new AICode();
        aiCode.setDeptId(ShiroUtils.getSysUser().getCompanyId());
        aiCode.setProductId(productId);
        map.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        map.put("productId", productId);
        //产品的AI码信息
        List<AICode> aiCodes = aiCodeMapper.selectAICodeByMaps(map);
        if (aiCodes.size() != 0) {
            aiCodeMapper.deleteAiCodeList(map);
        }
        return productMapper.removeProduct(productId);
    }

    /**
     * 查询生产管理类别
     *
     * @param managementCategory 管理类别
     * @return 结果
     */
    @Override
    public List<Scope> selectManagementCategory(Long managementCategory) {
        return productMapper.selectManagementCategory(managementCategory);
    }

    /**
     * 查询生产厂商
     *
     * @return 结果
     */
    @Override
    public List<DjManufacturer> selectManufacturer(Long companyId) {
        return productMapper.selectManufacturer(companyId);
    }

    /**
     * 查询产品信息
     *
     * @param productId 产品主键
     * @return 结果
     */
    @Override
    public Product selectProductById(Product productId) {
        Product product = productMapper.selectProductById(productId);
        return product;
    }

    /**
     * 查询产品规格信息
     *
     * @param productId 产品主键
     * @return 结果
     */
    @Override
    public List<ProductModel> selectProductByModelId(Product product) {
        return productMapper.selectProductByModelId(product);
    }

    /**
     * 修改产品信息
     *
     * @param
     * @return 结果
     */
    @Override
    @Transactional
    public String updateProduct(ProductAll productAll) {

        Long selectId = 0L;
        Product products = new Product();
        List<Product> productList = new ArrayList<>();
        List<ProductModel> productModelList = new ArrayList<>();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        products.setDeptId(sysUser.getDeptId());

        for (Product product : productAll.getProducts()) {
            products.setSelectId(product.getSelectId());
            products.setProductId(product.getProductId());
            productList = productMapper.selectProductList(products);
            productModelList = productMapper.selectProductByModelId(products);

        }

        ArrayList<Long> arrayList = new ArrayList();
        ArrayList<Long> productsList = new ArrayList();
        ArrayList<Long> productModels = new ArrayList<>();
        ArrayList<Long> arrayList1 = new ArrayList<>();

        try {
            if (productAll.getProducts() != null) {
                for (Product product : productList) {
                    arrayList.add(product.getSelectId());
                }
                for (Product product2 : productAll.getProducts()) {
                    if (product2.getProductProofAddress() != null && !product2.getProductProofAddress().isEmpty()) {
                        product2.setProductProofAddress(product2.getProductProofAddress().replaceAll("/profile/upload", ""));
                    }
                    product2.setProductId(product2.getProductId());
                    selectId = product2.getSelectId();

                    if (productMapper.selectProductSelectId(product2) == 1) {
                        productsList.add(selectId);
                        product2.setUpdateBy(sysUser.getUserName());
                        productMapper.updateProduct(product2);

                    } else if (product2.getSelectId() == 0 && product2.getProductName() != null) {
                        product2.setCompanyId(productAll.getCompanyId());
                        product2.setUpdateBy(sysUser.getUserName());
                        productMapper.insertProductId(product2);
                    }
                    if (productAll.getProductRelations() != null) {
                        productMapper.removeProductRelation(product2.getProductId());
                        for (ProductRelation productRelation : productAll.getProductRelations()) {
                            productRelation.setDeptId(SecurityUtils.getDeptId());
                            productRelation.setProductId(product2.getProductId());
                            productMapper.addMateProductRelation(productRelation);

                        }

                    }
                }
                TreeSet<Long> longs = new TreeSet<>();
                boolean b = arrayList.removeAll(productsList);
                for (Long along : arrayList) {
                    longs.add(along);
                }
                //修改数组中剩下的产品
                if (longs.size() != 0) {
                    for (Long aLong : longs) {
                        productMapper.deleteProduct(aLong);
                    }
                }

                for (ProductModel productModel : productModelList) {
                    arrayList1.add(productModel.getModelNo());
                }
                if (productAll.getProductModel() != null) {
                    for (ProductModel productModel : productAll.getProductModel()) {
                        Long modelNo = productModel.getModelNo();
                        if (productMapper.selectProductByModel(modelNo) == 1) {
                            productModels.add(modelNo);
                            productModel.setUpdateBy(sysUser.getUserName());
                            productMapper.updateProductModel(productModel);
                        } else if (productModel.getModelNo() == null && productModel.getModelCode() != null) {
                            productModel.setDeptId(sysUser.getDeptId());
                            productModel.setCreateBy(sysUser.getUserName());
                            productMapper.insertProductModel(productModel);
                        }
                    }
                    TreeSet<Long> longs1 = new TreeSet<>();
                    boolean c = arrayList1.removeAll(productModels);
                    for (Long along : arrayList1) {
                        longs1.add(along);
                    }
                    //删除数组
                    if (longs1.size() != 0) {
                        for (Long aLong : longs1) {
                            productMapper.deleteProductModel(aLong);

                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "1";
    }

    /**
     * 查询文件图片信息
     *
     * @param modelNo 产品规格明细
     * @return
     */
    @Override
    public List<PictureMemory> selectProductImg(Long modelNo) {
        return productMapper.selectProductImg(modelNo);
    }

    /**
     * 查询产品的规格型号是否唯一
     *
     * @param productModel
     * @return
     */
    @Override
    public Long selectProductProductType(ProductModel productModel) {
        return productMapper.selectProductProductType(productModel);
    }

    /**
     * 查询产品的产品唯一码是否唯一
     *
     * @param productModel 产品信息
     * @return 结果
     */
    @Override
    public Long selectProductModelCode(ProductModel productModel) {
        return productMapper.selectProductModelCode(productModel);
    }

    @Override
    public Product selectProductProofByMap(Map map) {
        Product productProof = productMapper.selectProductProofByMap(map);
        if (productProof == null) {
            return new Product();
        }
        return productProof;
    }

    /**
     * 根据产品型号唯一码和供应商主键查询产品型号信息
     *
     * @param supplierId 供应商
     * @param modelCode  产品型号唯一码
     * @return 结果
     */
    @Override
    public ProductModel selectProductByModelCode(Long supplierId, String modelCode) {
        return productMapper.selectProductByModelCode(supplierId, modelCode);
    }

    @Override
    public void importProduct(InputStream inputStream) throws IOException {
        Product product = new Product();
        try (XSSFWorkbook workbook = new XSSFWorkbook(inputStream);) {
            XSSFSheet sheet = workbook.getSheetAt(0); //Excel第一个页签
            int totalIndex = sheet.getLastRowNum();
            for (int rowIndex = 1; rowIndex <= totalIndex; rowIndex++) {
                XSSFRow row = sheet.getRow(rowIndex);
                if (row != null) {
                    for (int i = 0; i <= 21; i++) {
                        if (row.getCell(i) != null) {
                            row.getCell(i).setCellType(CellType.STRING);
                        } else {
                            row.createCell(i).setCellType(CellType.STRING);
                        }
                    }
                    if (row.getCell(0) != null) {
                        product.setProductId(Long.valueOf(row.getCell(0).getStringCellValue()));
                        product.setProductName(row.getCell(2).getStringCellValue());
                        product.setMedicalPerson(row.getCell(6).getStringCellValue());
                        product.setMedicalPhone(row.getCell(7).getStringCellValue());
                        product.setMedicalAddress(row.getCell(8).getStringCellValue());
                        product.setAgentName(row.getCell(13).getStringCellValue());
                        product.setYearType(row.getCell(14).getStringCellValue());
                        product.setYearRule(row.getCell(15).getStringCellValue());
                        product.setMonthType(row.getCell(16).getStringCellValue());
                        product.setMonthRule(row.getCell(17).getStringCellValue());
                        product.setDayType(row.getCell(18).getStringCellValue());
                        product.setDayRule(row.getCell(19).getStringCellValue());
                        productMapper.insertProduct(product);
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * PDA 扫码录入失效日期和产品主键 用于生成生产日期
     *
     * @param effectiveDate 失效日期
     * @param productId     产品主键
     * @return 结果
     */
    @Override
    public String calculateDate(String effectiveDate, Long productId) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Product product1 = new Product();
        product1.setProductId(productId);
        product1.setDeptId(sysUser.getCompanyId());
        Product product = productMapper.selectProductById(product1);
        String yearType = product.getYearType();
        String yearRule = product.getYearRule();
        String monthType = product.getMonthType();
        String monthRule = product.getMonthRule();
        String dayType = product.getDayType();
        String dayRule = product.getDayRule();

        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        Date parse = null;
        try {
            parse = sdf.parse(effectiveDate);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        if (parse == null) {
            throw new RuntimeException("时间计算错误，请重新设置");
        }
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(parse);

        if ("+".equals(dayType)) {
            rightNow.add(Calendar.DATE, parseInt(dayRule));
        } else {
            rightNow.add(Calendar.DATE, -parseInt(dayRule));
        }
        if ("+".equals(monthType)) {
            rightNow.add(Calendar.MONTH, parseInt(monthRule));
        } else {
            rightNow.add(Calendar.MONTH, -parseInt(monthRule));
        }
        if ("+".equals(yearType)) {
            rightNow.add(Calendar.YEAR, parseInt(yearRule));
        } else {
            rightNow.add(Calendar.YEAR, -parseInt(yearRule));
        }

        Date date = rightNow.getTime();

        String format = sdf.format(date);

        return format;
    }

    /**
     * 查询是否有产品使用该供应商
     *
     * @param productModel 产品型号规格
     * @return 结果
     */
    @Override
    public List<ProductModel> selectProductModel(ProductModel productModel) {
        return productMapper.selectProductModel(productModel);
    }

    /**
     * 根据产品ID和产品型号修改对应的 选择查询的天数 和 采购周期的时间
     * params:{
     "productId": '产品ID',
     "productType":"产品型号",
     "arrivalPeriod":"60",
     "comparisonPeriod":"180"
     * }
     * @param params
     * @return
     */
    @Override
    public List<WarehouseStatisticsVo> updateByPiAPt(Map<String, Object> params) {
        // 修改对应参数
        productMapper.updateByPiAPt(params);
        // 获取修改后的数据
        WarehouseStatisticsVo vo = new WarehouseStatisticsVo();
        try {
            vo.setProductId(Long.valueOf((Integer)params.get("productId")));
            vo.setProductType((String) params.get("productType"));
            vo.setArrivalPeriod(Long.valueOf((Integer) params.get("arrivalPeriod")));
            vo.setComparisonPeriod(Long.valueOf((Integer) params.get("comparisonPeriod")));
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
        return warehousingService.selectProductToWar_new(vo);
    }

}


